<?php
namespace App\Think\SdkGame;

class SEA{

    // 平台名称：BT宝特体育
    // 代理ID：81001
    // MD5Key ：5MBqNRKGQ55sfWwR
    // DesKey：hNFVygfDeCQpRA8W
    // 代理后台网址：https://ny.seagamingco.com/Admin/Main/index
    // 登入账号：BTagent
    // 登入密码：aa123456
    
    public function __construct()
    {
        $this->game_url = "https://h5.seagamingco.com/";

        // api地址
        $this->api_url = 'https://ny.seagamingco.com';
        $this->agent_id = '81001';

        $this->DesKey = 'hNFVygfDeCQpRA8W';
        $this->Md5key = '5MBqNRKGQ55sfWwR';
        $this->plat_type = 'SEA';
    }

    /**
     * 注册
     */
    public function register($param){
        $req_data = array(
            $param['account'],
            '',
            0,
            '',
            'H5'
        );
        $url = $this->build_request($req_data, 'AccountReg');
        $res = $this->sendRequest($url);
        return $res;
    }
    /**
     * 获取登录链接
     */
    public function login($param){
        // $reg_res = $this->register($param);
        // if($reg_res['code'] == -1) return $reg_res;

        $game_id  = isset($param['game_id']) ? $param['game_id'] : 320;
        $game_cat = $game_id==320 ? 2 : 1;
        $usertoken = isset($param['usertoken']) ? $param['usertoken'] : '';
        $aes = new SEAAes();
        $token = $aes->encrypt("{$this->agent_id},{$game_id},{$game_cat},{$param['account']}", $this->DesKey);
        $game_url = $this->game_url."$game_id/?agentid=".$this->agent_id."&token={$token}";
        //没有游戏ID，默认进入大厅
        if(!$param['game_id']){
            $device = isset($param['device']) ? $param['device'] : 'mobile';
            if($device == 'mobile') $game_url = "https://app.baote.com/web/index.html#/h5/gamelist?key=SEA&usertoken={$usertoken}";
            if($device == 'pc')     $game_url = "https://app.baote.com/web/index.html#/playing/gamelist?key=SEA&name=SEA%E7%94%B5%E5%AD%90&usertoken={$usertoken}";
        } 
        return ['code'=>1, 'url'=>$game_url ];
    }
    /**
     * 获取余额
     */
    public function balance($param){
        $req_data = array(
            $param['account']
        );
        $url = $this->build_request($req_data, 'AccountInfo');
        $res = $this->sendRequest($url);
        return [ 'code'=>$res['code'], 'balance'=>(float)$res['money'] ];
    }

    /**
     * 转入资金(上分)
     */
    public function transIn($param){
        $req_data = array(
            $param['account'],
            $param['money'],
            $param['orderid'],
        );
        $url = $this->build_request($req_data, 'AccountPay');
        $res = $this->sendRequest($url);
        return $res;
    }
    /**
     * 转出资金(下分)
     */
    public function transOut($param){
        $req_data = array(
            $param['account'],
            $param['money'],
            $param['orderid'],
        );
        $url = $this->build_request($req_data, 'AccountTakeout');
        $res = $this->sendRequest($url);
        return $res;
    }
    /**
     * 可转出资金查询(下分额度)
     */
    /*public function transOutInfo($param){
        $req_data = array(
            'action' => 15,
            'ts'     => time()*1000,
            'parent' => $this->parent,
            'uid'    => $param['account']
        );
        $url = $this->build_request($req_data);
        $res = $this->sendRequest($url);
        return $res;
    }*/

    /**
     * 游戏注单拉取
     */
    public function gameLogSync($param){
        $req_data = array(
            1,
            '',
            1,
            100000,
            0,
            "startTime" => strtotime($param['startTime']),
            "endTime"   => strtotime($param['endTime']),
        );
        $url = $this->build_request($req_data, 'GameRecord');
        $res = $this->sendRequest($url);
        
        //数据返回处理
        $list = @$res['data'];
        $rs = $raw_data = [];
        $status = 1;
        if(is_array($list) && count($list) > 0){

            foreach ($list as $k => $v) {

                $_tmp = $v;
                //相同订单号处理
                if(@$last_log['orderid'] == $_tmp['orderid']){
                    $_tmp['bet'] = $last_log['bet']+$_tmp['bet'];
                    $_tmp['award'] = $last_log['award']+$_tmp['award'];
                }

                //流水处理
                if($_tmp['award'] == 0){
                    $money_winlose = -$_tmp['bet'];
                    $money_valid = $_tmp['bet'];
                }  
                if($_tmp['award'] > 0){
                    $money_winlose = $_tmp['award']-$_tmp['bet'];
                    $money_valid = $money_winlose<$_tmp['bet'] ? $money_winlose : $_tmp['bet'];
                    if($money_valid<0) $money_valid = -$money_valid;
                }   
                //游戏记录处理
                $rs[$k] = [
                    'plat_type'     => $this->plat_type,
                    'game_type'     => $_tmp['game_typeid'],
                    'game_name'     => $_tmp['game_name'],
                    'game_user'     => $_tmp['account'],
                    'bet_id'        => $_tmp['orderid'],
                    'money_bet'     => $_tmp['bet'],
                    'money_valid'   => $money_valid,
                    'money_winlose' => $money_winlose,
                    'money_fee'     => 0,
                    'createtime'    => strtotime($_tmp['time']),
                    'updatetime'    => strtotime($_tmp['time']),
                    'status'        => $status,
                ];
                //源数据处理
                $raw_data[$k] = $_tmp;
                $raw_data[$k]['plat_type'] = $this->plat_type;
                $raw_data[$k]['bet_id']    = $_tmp['orderid'];
                $raw_data[$k]['status']    = $status;
                $raw_data[$k]['updatetime'] = strtotime($_tmp['time']);

                //相同订单特殊处理
                $last_log = $_tmp;
            }
        }
        // print_r($rs);
        $res['list'] = $rs;
        $res['raw_data']  = $raw_data;
        $res['code'] = $res['code'] == -16 ? 1 : $res['code'];
        return $res;
    }

    /**
     * 游戏列表
     */
    public function gameList($param){
        $req_data = array(
            1
        );
        $url = $this->build_request($req_data, 'GetGames');
        $res = $this->sendRequest($url);
        return @$res['data'];
    }


    /**
     * 业务 ======== start =========//
     */
    private function bet_status($status){
        return $status;
    }

    //游戏列表
    public function game_list(){
        $list = [
            ['id'=>308, 'name'=>'五色丹炉'],
            ['id'=>310, 'name'=>'经典7'],
            ['id'=>311, 'name'=>'大唐水果传'],
            ['id'=>312, 'name'=>'忍者联萌'],
            ['id'=>314, 'name'=>'幸运钟声'],
            ['id'=>316, 'name'=>'量子矩阵'],
            ['id'=>317, 'name'=>'呱呱！呱呱！'],
            ['id'=>318, 'name'=>'尼莫的遗产'],
            ['id'=>319, 'name'=>'皇冠小玛莉'],
            ['id'=>320, 'name'=>'哪吒'],
            ['id'=>321, 'name'=>'上仙劫'],
            ['id'=>701, 'name'=>'魔女交易'],
            ['id'=>702, 'name'=>'三国发'],
            ['id'=>801, 'name'=>'5PK'],
            ['id'=>325, 'name'=>'炼狱'],
            ['id'=>323, 'name'=>'万圣夜惊魂'],
            ['id'=>326, 'name'=>'农场物语'],
            ['id'=>328, 'name'=>'环游世界'],
            ['id'=>324, 'name'=>'红鲤鱼与绿鲤鱼'],
            ['id'=>330, 'name'=>'家有萌宝'],
        ];
        return $list;
    }
    //游戏名称
    public function game_name($gameid){
        $list = $this->game_list();
        foreach ($list as $k => $v) {
            if($v['id'] == $gameid) return $v['name'];
        }
        return '未知游戏';
    }


    /**
     * --------------
     * 内部方法
     * --------------
     */
    private function sendRequest($url,$post_data=array(), $req_type=0){
        $ch = curl_init();
        if($req_type == 1){  //POST
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        }else{ //GET
            $url = $url;
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $contents = curl_exec($ch);
        curl_close($ch);
        $contents = json_decode($contents, true);

        //业务处理
        $res = $contents;
        if(!isset($res['state'])) $res['code'] = -500;
        if($res['state'] > 0) $res['code'] = -$res['state'];
        if($res['state'] == 0) $res['code'] = 1;
        return $res;
    }
    
    private function build_request(array $param, $act='AccountPay'){
        
        $param = implode(',', $param);
        $aes = new SEAAes();
        $param = $aes->encrypt( $param, $this->DesKey );
        $param = urlencode($param);
        // $paraValue = urlencode(Aes::encrypt($param, $this->DesKey));
        // $key = md5($this->agent_id.$timestamp.$this->Md5key);
        
        $timestamp = time();
        $req_url = $this->api_url."/api/{$act}";
        $token = md5($this->agent_id.$timestamp.$this->Md5key);
        return $req_url.'?agent_id='.$this->agent_id."&param={$param}&time={$timestamp}&token={$token}";
    }
}


/*加密类*/
class SEAAes {
    
    // private $iv = "0102030405060708";//密钥偏移量IV，可自定义
    // private $encryptKey = "hNFVygfDeCQpRA8W";//AESkey，可自定义

    private $iv = "hNFVygfDeCQpRA8W";

    //加密
    public function encrypt($encryptStr, $DesKey='') {
        $localIV = $this->iv;
        $encryptKey = $DesKey;
        //Open module
        @$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV);
        //print "module = $module <br/>" ;
        @mcrypt_generic_init($module, $encryptKey, $localIV);
        //Padding
        @$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
        $pad = $block - (strlen($encryptStr) % $block); //Compute how many characters need to pad
        $encryptStr .= str_repeat(chr($pad), $pad); // After pad, the str length must be equal to block or its integer multiples
        //encrypt
        @$encrypted = mcrypt_generic($module, $encryptStr);
        //Close
        @mcrypt_generic_deinit($module);
        @mcrypt_module_close($module);
        return base64_encode($encrypted);
    }

    //解密
    public function decrypt($encryptStr, $DesKey='') {
        $localIV = $this->iv;
        $encryptKey = $DesKey;
        //Open module
        $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV);
        //print "module = $module <br/>" ;
        mcrypt_generic_init($module, $encryptKey, $localIV);
        $encryptedData = base64_decode($encryptStr);
        $encryptedData = mdecrypt_generic($module, $encryptedData);

        return $encryptedData;
    }
}